package com.lu.pojo.thread.syn;

/**
 * @author luzhenfang
 * @date 2020 05 24
 * @description  synchronized 同步代码块 确保线程安全
 */
public class TestBank {
    public static void main(String[] args) {
        Account1 account = new Account1(100, "个人资产");
        Drawing1 you = new Drawing1(account, 30, "你");
        Drawing1 wife = new Drawing1(account, 100, "你");
        you.start();
        wife.start();
    }

}


class Account1 {
    private int money;
    private String name;

    public int getMoney() {
        return money;
    }

    public void setMoney(int money) {
        this.money = money;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Account1(int money, String name) {
        this.money = money;
        this.name = name;
    }
}


// 模拟取款
class Drawing1 extends Thread {
    private Account1 account;// 账户
    // 取了多少钱
    private int drawingMoney;
    // 剩余多少钱
    private int nowMoney;

    public Drawing1(Account1 account, int drawingMoney, String name) {
        super(name);
        this.account = account;
        this.drawingMoney = drawingMoney;
    }


    // 取钱
    @Override
    public void run() {
        // 同步代码块 锁定可能会 出现冲突的对象 从而保证线程安全
        synchronized (account) {

            // 钱不够
            if (account.getMoney() - drawingMoney < 0) {
                System.out.println("余额不足!");
                return;
            }
            // 模拟网络延迟
            try {
                Thread.sleep(200);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            // 卡内余额 = 余额 - 你取的钱
            account.setMoney(account.getMoney() - drawingMoney);
            // 手里的钱
            nowMoney = nowMoney + drawingMoney;
            System.out.println("余额:" + account.getMoney());
            System.out.println("手里现金：" + nowMoney);
        }
    }

}
